#coding=utf-8
import time
import datetime
import requests
import json
import numpy as np
import pyaudio

#获取现在的时间
def getNowTime(format="%Y-%m-%d %H:%M:%S"):
    """
        获取现在的时间
    """
    return time.strftime(format, time.localtime())
    #return '2020-05-12'


def getTimeToFormatStr(format ="%Y-%m-%d %H:%M:%S",ltime =time.localtime()):
    """
        获取现在的时间
    """
    return time.strftime(format, time.localtime(ltime))
    #return '2020-05-12'


def getYesterday():
    """
        获取昨天的时间
    """
    today=datetime.date.today()
    oneday=datetime.timedelta(days=1)
    yesterday=today-oneday
    return yesterday
    #return '2020-06-26'

def dif_time(a,b):
    """
    计算两个时间之间差值
    :param a:
    :param b:
    :return: 返回时间差
    """
    d1 = datetime.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
    d2 = datetime.datetime.strptime(b, '%Y-%m-%d %H:%M:%S')
    #间隔天数
    day = (d2 - d1).days
    #间隔秒数
    second = (d2 - d1).seconds
    return second

"""
#addtodict(dict,a["id"],a["name"],a["value"])
"""
def addtodictTwo(thedict, key_a, key_b, val):
    """
    list dict 转 dict
    :param thedict: 存入数据的dict
    :param key_a:  外层key
    :param key_b:  内层key
    :param val:  value
    :return:  存入数据的dict
    """
    if key_a in thedict:
        thedict[key_a].update({key_b: val})
    else:
        thedict.update({key_a:{key_b: val}})

def addtodictOne(thedict, key_a, val):
    """
    map 转 id为主键的dict
    :param thedict: 存入数据的dict
    :param key_a: id
    :param val: value
    :return: 存入数据的dict
    """
    if key_a in thedict:
        thedict[key_a].update(val)
    else:
        thedict.update({key_a:val})

def getGzName(keys):
    """
    :param keys: name
    :return:  value
    """
    d = {"水泵故障": "1", "风机故障": "2"}
    s = []
    for k in keys:
        if k in d.keys():
            s.append(d.get(k))
    return ','.join(s)


def blockPrint(sys,os):
    """
    关闭日志
    :param sys:
    :param os:
    :return:
    """
    sys.stdout = open(os.devnull, 'w')

def enablePrint(sys,os):
    """
    开启日志
    :param sys:
    :param os:
    :return:
    """
    sys.stdout = sys.__stdout__

def listToDict(list,key):
    """
    list 转 dict
    :param list:
    :param mn:
    :return:
    """
    dict = {}
    for a in list:
        try:
            addtodictOne(dict, a[key], a)
        except:
            print("该数据没有id", a)
        else:
            print("该数据组装成功", a)
    return dict

def timeAdd(dict={}, key="", time=0):
    """
    详细故障时间相加
    :param dict:
    :param time:
    :return:
    """
    if key in dict.keys():
        atime = float(dict.get(key)) + time
        dict[key] = atime
    else:
        dict[key] = time

    return dict

def get_and_set_dict(vals,key="id"):
    result = {}
    for val in vals:
        if type(val) == str:
            val = eval(val.replace("null", "''"))
        addtodictOne(result,val[key],val)
    return result

def get(url, message):
    print(message + "接口start" + url)
    url = url
    headers = {'content-type': 'application/json'}
    ret = requests.get(url, headers=headers)
    text = json.loads(ret.text)
    ting(text["data"])
    print(message + "接口end")
    return text

class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, datetime.date):
            return obj.strftime("%Y-%m-%d")

        else:
            return json.JSONEncoder.default(self, obj)


def digital_to_chinese(digital):
    str_digital = str(digital)
    chinese = {'1': '一', '2': '二', '3': '三', '4': '四', '5': '五', '6': '六', '7': '七', '8': '八', '9': '九', '0': '零'}
    chinese2 = ['拾', '佰', '仟', '万']
    jiao = ''
    bs = str_digital.split('.')
    yuan = bs[0]
    if len(bs) > 1:
        jiao = bs[1]
    r_yuan = [i for i in reversed(yuan)]
    count = 0
    for i in range(len(yuan)):
        if i == 0:
            # r_yuan[i] += '圆'
            continue
        r_yuan[i] += chinese2[count]
        count += 1
        if count == 4:
            count = 0
            chinese2[3] = '亿'

    s_jiao = [i for i in jiao][:3]  # 去掉小于厘之后的

    j_count = -1
    for i in range(len(s_jiao)):
        s_jiao[i] += chinese2[j_count]
        j_count -= 1
    last = [i for i in reversed(r_yuan)] + s_jiao

    last_str = ''.join(last)
    last_str = last_str.replace('0百', '0').replace('0十', '0').replace('000', '0').replace('00', '0').replace('0圆', '圆')
    for i in range(len(last_str)):
        digital = last_str[i]
        if digital in chinese:
            last_str = last_str.replace(digital, chinese[digital])
    return last_str

def to_chinese(str):
    chinese = {'1': '一', '2': '二', '3': '三', '4': '四', '5': '五', '6': '六', '7': '七', '8': '八', '9': '九', '0': '零', "#": "井"}
    str_arr = []
    for i in str:
        if i in chinese.keys():
            str_arr.append(chinese[i])
        else:
            str_arr.append(i)
    return "".join(str_arr)

def ting(arrlist):
    ndarray = np.array(arrlist)
    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paFloat32,
                         channels=1,
                         rate=36000,
                         output=True
                         )
    # Assuming you have a numpy array called samples
    data = ndarray.astype(np.float32).tostring()
    stream.write(data)